from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import redis_store
from info.constants import CLICK_RANK_MAX_NEWS
from info.models import User, News, Category
from info.utils.common import user_status_monitoring
from info.utils.response_code import RET
from . import index_url


# 展示主页以及点击排行榜以及导航栏以及登陆用户信息
@index_url.route('/')
@user_status_monitoring
def index():
    # 点击排行榜单的实现
    # 1.数据库里面查询 按照点击量
    news = []
    try:
        news = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 2.出去查询的数据
    new_list = []
    for new in news:
        new_list.append(new.to_basic_dict())

    # 显示导航栏
    category = Category.query.all()

    item_list = []
    for item in category:
        item_list.append(item.to_dict())

    # 主页右上角的用户信息和登陆/注册 的渲染
    # 1.判断当前是登陆状态（session中判断是否登陆）
    # user_id = session.get('user_id', None)
    # # 2.是的话就取出用户的信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user
    # 3.把用户信息取出 通过模板渲染出来
    data = {
        'user': user.to_dict() if user else None,
        'new_list': new_list,
        'item_list': item_list
    }
    # 4.如果不存在就设置默认模板
    return render_template('news/index.html', data=data)


# 显示页面左上角的小图标
@index_url.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


# 显示全部新闻列表
@index_url.route('/news_list')
def news_list():
    # 1.获取参数
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)

    # 2.校验参数的格式（参数都是int格式)
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')

    # 3.取出数据
    filters = [News.status == 0]
    if cid != 1:
        filters.append(News.category_id == cid)

    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page)

    totalPage = paginate.pages  # 总页数
    currentPage = paginate.page  # 当前页数
    home_news_list = []
    for new in paginate.items:
        home_news_list.append(new.to_dict())

    data = {
        'home_news_list': home_news_list,
        'totalPage': totalPage,
        'currentPage': currentPage
    }

    # 4.返回查询结果
    return jsonify(errno=RET.OK, errmsg='查询成功', data=data)
